import re, uiautomation as auto
import sys

TITLE_PATTERNS = [r'.*BOSS直聘.*']            # 标题模糊匹配
CHROME_CLASSES = {'Chrome_WidgetWin_0', 'Chrome_WidgetWin_1'}
MAX_DEPTH = 100
SEARCH_TMO = 3.0
PER_ITEM_TMO = 3.0

def list_top_windows():
    root = auto.GetRootControl()
    rows = []
    for w in root.GetChildren():
        try:
            rows.append((w.ControlTypeName, w.Name or '', w.ClassName or '', w))
        except Exception:
            pass
    for i, (t, n, c, _) in enumerate(rows, 1):
        print(f"{i:02d}. type={t:14} name='{n}' class='{c}'",file=sys.stderr)
    return rows

def name_matches(name: str) -> bool:
    return any(re.fullmatch(pat, name or '') for pat in TITLE_PATTERNS)


def get_boss_window(timeout: float = 3.0):
    """
    获取 BOSS直聘 根控件（WindowControl 或 PaneControl）
    :param timeout: 查找超时，秒
    :return: Control 对象或 None
    """
    with auto.UIAutomationInitializerInThread():
        auto.SetGlobalSearchTimeout(0.5)

        # 1) 先尝试 WindowControl（标准顶层窗口）
        win = auto.WindowControl(RegexName=r'.*BOSS直聘.*', searchDepth=1)
        if win.Exists(timeout, 0.2):
            return win

        # 2) 回退：在顶层 PaneControl 里找（Electron/Chromium 应用常见）
        root = auto.GetRootControl()
        for c in root.GetChildren():
            if 'BOSS直聘' in (c.Name or '') and c.ClassName in ('Chrome_WidgetWin_0', 'Chrome_WidgetWin_1'):
                return c

    print("❌ 未找到 BOSS直聘 窗口",file=sys.stderr)

    return None


def pick_boss_root():
    """返回最合理的 BOSS 根节点（Window 或 Pane）"""
    # 1) 先尝试 WindowControl（如果 BOSS 是真正的顶层窗口）
    for pat in TITLE_PATTERNS:
        win = auto.WindowControl(RegexName=pat, searchDepth=1)
        if win.Exists(SEARCH_TMO, 0.2):
            return win

    # 2) 回退：在顶层子控件中找 PaneControl + Class=Chrome_WidgetWin_* + Name 匹配
    tops = list_top_windows()  # 也顺便打印出来方便你核对
    candidates = []
    for _, name, cls, elem in tops:
        if cls in CHROME_CLASSES and name_matches(name):
            candidates.append(elem)

    if candidates:
        # 取面积最大者作为根
        def area(e):
            try:
                r = e.BoundingRectangle
                return max(0, (r.right - r.left)) * max(0, (r.bottom - r.top))
            except Exception:
                return -1
        return max(candidates, key=area)

    return None


def get_all_texts(root_ctrl, max_depth=None):
    """
    遍历 root_ctrl 下的所有子孙，收集 Text/Document 控件的 Name
    """
    texts = []

    def walk(ctrl, depth=0):
        if max_depth is not None and depth > max_depth:
            return
        try:
            children = ctrl.GetChildren()
        except Exception:
            return
        for c in children:
            try:
                if c.ControlTypeName in ('TextControl', 'GroupControl'):
                    if c.Name:  # 去掉空
                        texts.append(c.Name.strip())
            except Exception:
                pass
            walk(c, depth+1)

    walk(root_ctrl)
    return texts

def is_visible(ctrl):
    try:
        if ctrl.IsOffscreen:
            return False
        r = ctrl.BoundingRectangle
        if r.right <= r.left or r.bottom <= r.top:
            return False
        # 判断是否在屏幕范围内
        from ctypes import windll
        sw = windll.user32.GetSystemMetrics(0)
        sh = windll.user32.GetSystemMetrics(1)
        if r.right <= 0 or r.bottom <= 0 or r.left >= sw or r.top >= sh:
            return False
        return True
    except Exception:
        return False

'''
消息数量: []
消息信息: ['08月12日', '李美丽', '品类运营', '[我已读]', '你好，请问还招聘吗？']
坐标 (553, 1829)


消息数量: ['1']
消息信息: ['08月12日', '姜迎迎', '品类运营', '[未读]', '您好，上班时间是怎样的？']
坐标 (553, 1965)


消息数量: ['2']
消息信息: ['08月11日', '顾路臣', '品类运营', '[未读]', '吗']
坐标 (553, 2102)
'''


def execute(win, post):
    try:
        with auto.UIAutomationInitializerInThread():
            # win = get_boss_window()  # pick_boss_root()
            if win == None:
                win = get_boss_window()
            if post is None:
                print("post不能为空", file=sys.stderr)
                return False

            win.Exists(3, 0.2)  # 超时等待
            newGenius = auto.ListItemControl(searchFromControl=win, Name='新牛人')

            newGeniusParent = newGenius.GetParentControl().GetParentControl()
            if len(newGeniusParent.GetChildren()) == 2:
                newGeniusParent.GetChildren()[1].Click()
            else:
                filter = auto.TextControl(searchFromControl=newGenius.GetParentControl().GetParentControl(), Name='筛选')
                parent = filter.GetParentControl().GetParentControl().GetParentControl().GetParentControl().GetPreviousSiblingControl().GetPreviousSiblingControl()
                # parent = newGenius.GetParentControl().GetNextSiblingControl()
                parent.Click()

            # 请输入职位名称 Edit
            search = auto.EditControl(searchFromControl=win, Name='请输入职位名称')

            # 品类运营 _ 淮北 1-3K
            # auto.TextControl(searchFromControl= search.GetParentControl().GetNextSiblingControl(), Name='品类运营 _ 淮北 1-3K').Click()
            auto.TextControl(searchFromControl=search.GetParentControl().GetNextSiblingControl(), Name=post).Click()

            return True
    except Exception as e:
        # 打印异常信息以便调试
        # print(f"执行过程中发生错误: {str(e)}", file=sys.stderr)
        return False

# print('开始执行')
# results = execute(None,'临时电工 _ 淮北 3-4K')
# print(results)